<?php
namespace Qgs\Controller;

/**
 * 优惠卷
 * Class DiscountCouponController
 * @package Qgs\Controller
 */
class DiscountCouponController extends BaseController
{
    public $local_id;

    public function __construct()
    {
        parent::__construct();
        $this->local_id = session('userInfo')['local_id'];
    }

    public function index()
    {
        $time = date('Y-m-d H:i:s', time());
        $type = I('type');
        if ($type == 'timeout') {
            $where['end_time'] = ['LT', $time];
        } else {
            $where['end_time'] = ['EGT', $time];
        }

        // 排序
        $order = I('param.order', 'desc');
        $order == 'asc' ? 'desc' : 'asc';
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign(['order' => $sunxu]);
        $order = ['id' => $order];

        $where['local_id'] = $this->local_id;

        $b2c_discount_coupon = M('b2c_discount_coupon');

        $count = $b2c_discount_coupon->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出

        $discount_coupon_msg = $b2c_discount_coupon->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();

        foreach ($discount_coupon_msg as &$v) {
            $v['type_name'] = $this->CouponType($v['type']);
            $v['type_money'] = $this->CouponMoney($v);
        }


        $this->assign([
            'discount_coupon_msg' => $discount_coupon_msg,
            'show' => $show
        ]);
        $this->display();
    }

    /**
     * 添加优惠券
     */
    public function add()
    {

        if (!IS_POST) {
            $this->display();
        } else {
            $name = I("name"); //优惠卷名称
            $description = I("description"); //优惠卷说明
            $paita = I("paita"); //排他功能
            $type = I("type"); //优惠类型
            $money_price = I("money_price"); //1现金优惠券
            $man_price = I("man_price"); //2订单金额满
            $youhui_price = I("youhui_price"); //2订单优惠
            $goods_price = I("goods_price"); //3商品优惠
            $goods_id_array = I("goods_id_array"); //3商品id
            $start_time = I("start_time");
            $end_time = I("end_time");
            $sort = I("sort");

            if (strtotime($start_time) >= strtotime($end_time)) {
                $this->error('开始时间不能大于结束时间');
            }

            // 优惠券和订单优惠默认是不需要包含商品的,商品优惠是包含商品的
            if ($type == 3) {
                $is_include = '1'; // 包含商品 is_include字段为1
            }else {
                $is_include = '0';
            }

            $time = date("Y-m-d H:i:s", time());
            $data = [
                'name' => $name,
                'description' => $description,
                'is_include' => $is_include,
                'paita' => $paita,
                'type' => $type,
                'money_price' => $money_price,
                'man_price' => $man_price,
                'youhui_price' => $youhui_price,
                'goods_price' => $goods_price,
                'goods_id_array' => $goods_id_array,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'created_at' => $time,
                'sort' => $sort,
                'local_id' => $this->local_id
            ];
            $discount_coupon = M('b2c_discount_coupon')->add($data);
            if ($discount_coupon) {
                $this->success('添加成功','/Qgs/DiscountCoupon/index');
            } else {
                $this->error('添加失败');
            }
        }
    }

    /**
     * 获取类型
     * @param $i
     * @return string
     */
    public function CouponType($i)
    {
        switch ($i) {
            case 1:
                $msg = '现金券';
                break;
            case 2;
                $msg = '订单优惠券';
                break;
            case 3;
                $msg = '商品优惠券';
                break;
        }
        return $msg;
    }

    public function CouponMoney($v)
    {
        switch ($v['type']) {
            case 1:
                $money = $v['money_price'];
                break;
            case 2;
                $money = $v['youhui_price'];
                break;
            case 3;
                $money = $v['goods_price'];
                break;
        }
        return $money;
    }

    /**
     * 添加产品
     */
    public function productAdd()
    {

        $name = I('name', '', htmlspecialchars());
        $id = I('id', '', htmlspecialchars());

        if (!empty($name)) {
            $where['b.name'] = array('like', "%$name%");
        }

        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 20);

        $order = "a.store_pid desc";
        $product_relation_model = M('b2c_store_product a');

        $where['a.local_id'] = $this->local_id;
        $where['a.store_status'] = 'true';
        $where['b.disabled'] = 'false';

        $field = "a.marketprice,a.price,a.store,a.discount,a.store_pid,b.product_id,b.goods_id,b.title,b.name,b.spec_info";

        // 可售货品
        $count = $product_relation_model->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id')
            ->where($where)
            ->count();

        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $product_relation_msg = $product_relation_model->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id', 'left')
            ->where($where)
            ->order($order)
            ->field($field)
            ->page($page, $num)
            ->select();

//        $menu = M('store_carousel')->where(['id' => $id])->find();
//        $value = unserialize($menu['value']);

        $this->assign([
            'product_relation_msg' => $product_relation_msg,
            'show' => $show,
            'id' => $id,
//            'value' => $value
        ]);

        $this->display();
    }

    /**
     * 删除
     */
    public function delete()
    {
        $id = I('id');
        $discount_coupon = M('b2c_discount_coupon');

        $time = date('Y-m-d H:i:s', time());

        $where['end_time'] = ['LT', $time];
        $where['id'] = $id;
        $where['local_id'] = $this->local_id;

        $discount_coupon_msg = $discount_coupon->where($where)->find(); // 不能删除没结束的优惠券
        if (empty($discount_coupon_msg)) {
            $this->error('该优惠券结束时间还没到，不能删除', U('DiscountCoupon/index'));
        }

        $discount_coupon->where(['id' => $id])->delete();
        $this->success('成功删除');
    }

    /**
     * 修改
     */
    public function update()
    {
        $id = I('id');
        $discount_coupon = M('b2c_discount_coupon');
        $time = date('Y-m-d H:i:s', time());
        $where['end_time'] = ['EGT', $time];
        $where['id'] = $id;
        $where['local_id'] = $this->local_id;
        $discount_coupon_msg = $discount_coupon->where($where)->find();
        if (empty($discount_coupon_msg)) {
            $this->error('有误');
        }

//        if ($discount_coupon_msg['type'] == '3' || $discount_coupon_msg['type'] == '2') {
        $array_goods_id = explode('#', $discount_coupon_msg['goods_id_array']);
        $array_goods_id = implode(',', $array_goods_id);
        $products = M('b2c_products a')->field('a.product_id,a.name,a.spec_info,b.store_pid')
            ->join(C('DB_PREFIX') . 'b2c_store_product b on a.product_id=b.product_id', 'left')
            ->where(['b.store_pid' => ['in', $array_goods_id], 'a.disabled' => 'false'])
            ->select();

        $this->assign(['products' => $products]);
//        }


        $this->assign(['msg' => $discount_coupon_msg]);
        $this->display();
    }

    /**
     * 修改
     */
    public function postUpdate()
    {
        if (IS_POST) {
            $id = I('id');
            $time = date('Y-m-d H:i:s', time());

            $where['end_time'] = ['EGT', $time];
            $where['id'] = $id;
            $where['local_id'] = $this->local_id;

            $discount_coupon = M('b2c_discount_coupon');
            $discount_coupon_msg = $discount_coupon->where($where)->find();

            if (empty($discount_coupon_msg)) {
                $this->error('有误');
            }

            $name = I("name"); //优惠卷名称
            $description = I("description"); //优惠卷说明
            $paita = I("paita"); //排他功能
            $type = I("type"); //优惠类型
            $money_price = I("money_price"); //1现金优惠券
            $man_price = I("man_price"); //2订单金额满
            $youhui_price = I("youhui_price"); //2订单优惠
            $goods_price = I("goods_price"); //3商品优惠
            $goods_id_array = I("goods_id_array"); //3商品id
            $start_time = I("start_time");
            $end_time = I("end_time");
            $sort = I("sort");

            if (strtotime($start_time) >= strtotime($end_time)) {
                $this->error('开始时间不能大于结束时间');
            }

            // 优惠券和订单优惠默认是不需要包含商品的,商品优惠是包含商品的
            if ($type == 3) {
                $is_include = '1'; // 包含商品 is_include字段为1
            }else {
                $is_include = '0';
            }

            $data = [
                'name' => $name,
                'description' => $description,
                'is_include' => $is_include,
                'paita' => $paita,
                'type' => $type,
                'money_price' => $money_price,
                'man_price' => $man_price,
                'youhui_price' => $youhui_price,
                'goods_price' => $goods_price,
                'goods_id_array' => $goods_id_array,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'created_at' => $time,
                'sort' => $sort,
            ];
            $where['local_id'] = $this->local_id;
            $where['id'] = $id;

            $discount_coupon = M('b2c_discount_coupon')->where($where)->save($data);
            if ($discount_coupon) {
                $this->success('修改成功', U('DiscountCoupon/index'));
            } else {
                $this->error('修改失败');
            }

        } else {
            $this->error('有误');
        }
    }

    /**
     * 判断排序是否重复
     */
    public function ajaxSort()
    {
        if (IS_AJAX) {
            $sort = I('sort');
            $id = I('id');
            $time = date('Y-m-d H:i:s', time());

            $where['end_time'] = ['EGT', $time];
            $where['sort'] = $sort;
            $where['local_id'] = $this->local_id;
            if ($id) {
                $where['id'] = ['NEQ', $id];
            }


            $discount_coupon = M('b2c_discount_coupon');
            $discount_coupon_msg = $discount_coupon->where($where)->find(); // 查询进心中是否有相同的sort排序
            $flag = 0;
            if ($discount_coupon_msg) {
                $flag = 1;
            }
            echo $flag;
        }
    }

    /**
     * 兑换码
     */
    public function exchangeCode()
    {
//        $time = date('Y-m-d H:i:s', time());
        $id = I('id'); // 优惠券id

        $where['local_id'] = $this->local_id;
        $where['id'] = $id;
//        $where['end_time'] = ['GT', $time];

        $discount_coupon = M('b2c_discount_coupon');
        $discount_coupon_msg = $discount_coupon->where($where)->find();

        if (empty($discount_coupon_msg)) {
            $this->error('有误');
        }

        $coupon_code = M('b2c_discount_coupon_code');

        // 兑换码条件
        $where_code = [
            'local_id' => $this->local_id,
            'discount_coupon_id' => $id,
        ];

        $count = $coupon_code->where($where_code)->count();// 查询满足要求的总记录数

        $Page = new \Think\Page($count, 50);// 实例化分页类 传入总记录数和每页显示的记录数(20)
        $show = $Page->show();// 分页显示输出

        $coupon_code_msg = $coupon_code->where($where_code)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign([
            'msg' => $coupon_code_msg,
            'show' => $show
        ]);
        $this->display();
    }

    public function getExchangeCode()
    {
/*        $xlsName  = "怡臣电子商务";
        $xlsCell  = array(
            array('0','账号序列'),
            array('1','登录账户'),
            array('2','账户昵称'),
            array('3','222222222222')
        );

        $xlsData  = array(
            array('0' => ' 123', '1' => ' 234234234', '2' => ' 2222222222', '3'=>' 222222222222'),
            array('0' => ' 123', '1' => ' 234234234', '2' => ' 2222222222', '3'=>' 222222222222'),
            array('0' => ' 123', '1' => ' 234234234', '2' => ' 2222222222', '3'=>' 222222222222'),
            array('0' => ' 123', '1' => ' 234234234', '2' => ' 2222222222', '3'=>' 222222222222'),
        );

        exportExcel($xlsName,$xlsCell,$xlsData);exit;*/
        if (empty($_GET['num'])) {
            $this->error('数量不能为空');
        }
        $time = date('Y-m-d H:i:s', time());
        $id = I('id'); // 优惠券id

        $where['local_id'] = $this->local_id;
        $where['id'] = $id;
        $where['end_time'] = ['GT', $time];

        $discount_coupon = M('b2c_discount_coupon');
        $discount_coupon_msg = $discount_coupon->where($where)->find();

        if (empty($discount_coupon_msg)) {
            $this->error('过期或者有误不能下载');
        }
        $coupon_code = M('b2c_discount_coupon_code');
        // 生成兑换码
        if ($_GET['num']) {
            $num = I('num');
            if ($num <= 0) {
                var_dump($num);exit;
            }

            for ($i = 1; $i <= $num; $i++) {
//                $code = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $this->randomkeys(10);
                $code = getrandstr(10);
                $data = [
                    'local_id' => $this->local_id,
                    'code' => $code,
                    'discount_coupon_id' => $id,
                    'created_at' => $time
                ];
                $coupon_code->add($data);
                $codes[] = ['0'=> ' '.$code];
            }
        }


        $xlsName  = "怡臣电子商务";
        $xlsCell  = array(
            array('0','优惠券码'),
        );

        exportExcel($xlsName,$xlsCell,$codes);exit;

    }

    /**
     * 生成随机数
     * @param $length 生成随机数长度
     * @return string
     */
    public function randomkeys($length)
    {
        $pattern='1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,35)};    //生成php随机数
        }
        return $key;
    }


}
